import cron from 'node-cron';
import db from './mysqlHelper.js';
import logger from './logger.js';
import moment from 'moment';
import redis from './redis.js';

//每天凌晨1点生成日报表
cron.schedule('0 1 * * *', async () => {
    await make_day_report();
});

async function sleep(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

async function make_day_report() {
    let day_data = {
        statistical_date: moment().subtract(1, 'days').format('YYYY-MM-DD'),
        order_num: 0,
        order_amt: 0,
        cash_amt: 0,
        qualified_count: 0
    };
    let start_time = moment().subtract(1, 'days').format('YYYY-MM-DD 00:00:00');
    let end_time = moment().subtract(1, 'days').format('YYYY-MM-DD 23:59:59');

    //获取订单表中的现金支付金额
    let sql = `SELECT SUM(price) as price FROM order_info WHERE pay_type=0 AND pay_status=1 AND check_time BETWEEN '${start_time}' AND '${end_time}'`;
    console.log(sql);
    let result = await db.query(sql);
    if (result.length == 0 || result[0].price == null) {
        logger.error(`未获取到现金支付金额`);
        day_data.cash_amt =0;
    }else{
        day_data.cash_amt = result[0].price;
    }


    //获取订单表中的微信支付金额
    sql = `SELECT SUM(price) as price FROM order_info WHERE pay_type=1 AND pay_status=1 AND check_time BETWEEN '${start_time}' AND '${end_time}'`;
    result = await db.query(sql);
    let wechat_price =0;
    if (result.length == 0 || result[0].price == null) {
        logger.error(`未获取到微信支付金额`);
    }
    else{
        wechat_price = result[0].price;
    }
    day_data.order_amt = day_data.cash_amt + wechat_price;

    //获取当天检测的总订单数
    sql = `SELECT COUNT(*) as count FROM order_info WHERE check_time BETWEEN '${start_time}' AND '${end_time}'`;
    result = await db.query(sql);
    if (result.length == 0 || result[0].count == null) {
        logger.error(`生成日报表失败,未获取到订单总数`);
        day_data.order_num = 0;
        return;
    }else{
        day_data.order_num = result[0].count;
    }

    //获取当天检测合格的订单数
    sql = `SELECT COUNT(*) as count FROM order_info WHERE status=2 AND check_time BETWEEN '${start_time}' AND '${end_time}'`;
    result = await db.query(sql);
    if (result.length == 0 || result[0].count == null) {
        logger.error(`生成日报表失败,未获取到合格订单数`);
        day_data.qualified_count =0;
    }else{
        day_data.qualified_count = result[0].count;
    }

    //将数据插入日报表
    let res = await db.create('day_report', day_data);
    if (res instanceof Error) {
        logger.error(`生成日报表失败,插入数据失败:${res.message} 日报数据 ${JSON.stringify(day_data)}`);
        return;
    }
    logger.info(`生成日报表成功,日报数据 ${JSON.stringify(day_data)}`);
}

make_day_report();